//
//  AIGirlPurchaseManager.swift
//  AIGirl
//
//  Created by Rae on 2024/1/30.
//

import Foundation
import SwiftyStoreKit

let purchaseTool = AIGirlPurchaseManager.shared

class AIGirlPurchaseManager: NSObject, UorInXNetworkProtocol, ObservableObject {

    static let shared = AIGirlPurchaseManager()
    
    var transactionInfo: String? {
        get { UserDefaults.standard.string(forKey: "AIGirl_recharge_transactionInfo") }
        set { UserDefaults.standard.setValue(newValue, forKey: "AIGirl_recharge_transactionInfo") }
    }
    
    func purchaseProduct(productCode: String, productId: String) {
        
        Task{
            ToastTool.show()
            guard let _ = await self.createOrder(productId: productId) else {
                return
            }
            AIGirlApplePay.default.buy(productCode, type: 0)
//            let result1 = await StoreKitTool.purchaseProduct(purchaseID: product.productIdentifier, orderNo: "" )
//            guard let verifyData = result1.data else {
//                ToastTool.dismiss()
//                return
//            }
//            guard let ticket = verifyData.1 else {
////                "payId 为空".toast_error
//                ToastTool.dismiss()
//                return
//            }
//            request.start(.VerifyTransaction(baseStr: ticket)) { result in
//                if result.isSuccessful {
//                    /// 清空缓存
//                    AIGirlApplePayCache.shared.productIdentifier = nil
//                    
//                    SwiftyStoreKit.finishTransaction(verifyData.0.transaction)
//                    GlobalTool.refreshUserInfo()
//                }else {
//                    result.errorDescripton?.toast_error
//                    
//                    AIGirlApplePayCache.shared.productIdentifier = ticket
//                }
//            }
        }
    }
    
    private func verify(info: String) {
        
    }

    func createOrder(productId: String) async -> AIGirlPurchaseModel? {
        await withCheckedContinuation { continuation in
            request.start(.DoOrder(listId: productId), type: AIGirlPurchaseModel.self, isLoading: false) { result in
                if result.isSuccessful, let model = result.model {
                    continuation.resume(returning: model)
                } else {
                    continuation.resume(returning: nil)
                }
            }
        }
    }
    
//    private func checkOrder(ticket: String) async -> AIGirlPurchaseModel? {
//        await withCheckedContinuation { continuation in
//            request.start(.DoOrder(listId: productId), type: AIGirlPurchaseModel.self, isLoading: false) { result in
//                if result.isSuccessful, let model = result.model {
//                    continuation.resume(returning: model)
//                } else {
//                    continuation.resume(returning: nil)
//                }
//            }
//        }
//    }
}
